package com.laiyima.zhongjiang.linghuilv.demo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.laiyima.zhongjiang.linghuilv.demo.util.PrivacyActivity;
import com.laiyima.zhongjiang.linghuilv.demo.util.UserAgreementActivity;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class FirstActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView goto_Register,forget_pw,login_xieyi,login_zhengce;
    private Button First_next_button;
    private CheckBox myCheckBox;
    private String TAG="FistActivity";
    private Boolean canClick=false,canClick1=false,canClick2=false,pW_show=false;
    private EditText inputNumber,inputPassword;
    private int logCode;
    private int pw_leng;
    private ImageView imageView,login_agent;
    private String userID,role;
    private int nl,pl, cb=1;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.CAMERA"
    };

    private boolean isHideFirst = true;
    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static final int TIME_EXIT=3000;
    private static int isExit=0;


    //实现按两次后退才退出
    private CountDownTimer mCountDownTimer1 = new CountDownTimer(TIME_EXIT,1000) {
        @Override
        public void onTick(long l) {
            isExit++;
        }

        @Override
        public void onFinish() {
            isExit=0;
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK){
            exit();
            return false;
        }
        return super.onKeyDown(keyCode,event);
    }
    private void exit(){
        if(isExit<1){
            Toast.makeText(getApplicationContext(),"再点击一次返回退出程序",Toast.LENGTH_SHORT).show();
            mCountDownTimer1.start();
        }else{
            isExit=0;

            mCountDownTimer1.cancel();
            Toast.makeText(getApplicationContext(),"退出程序",Toast.LENGTH_SHORT).show();
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
            System.exit(0);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        inputNumber = findViewById(R.id.inputNumber);
        Drawable drawable1 = getResources().getDrawable(R.drawable.shouji);
        drawable1.setBounds(0, 0, 50, 60);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        inputNumber.setCompoundDrawables(drawable1, null, null, null);//只
        inputPassword=findViewById(R.id.inputPassword);
        Drawable drawable = getResources().getDrawable(R.drawable.mima);
        Drawable drawable2 = getResources().getDrawable(R.drawable.xianshi);
        drawable.setBounds(0, 0, 60, 60);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        drawable2.setBounds(0, 0, 60, 40);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        inputPassword.setCompoundDrawables(drawable, null, drawable2, null);//只
        First_next_button =findViewById(R.id.first_next_button);
         imageView=findViewById(R.id.imageView_PW);
        goto_Register=findViewById(R.id.register_TV);
        forget_pw=findViewById(R.id.forget_pw);
        verifyStoragePermissions(this);
        inputNumber.setCompoundDrawablePadding(40);
        inputPassword.setCompoundDrawablePadding(40);
        final int eyeWidth = drawable2.getBounds().width();// 眼睛图标的宽度
        inputPassword.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    float et_pwdMinX = v.getWidth() - eyeWidth - inputPassword.getPaddingRight();
                    float et_pwdMaxX = v.getWidth();
                    float et_pwdMinY = 0;
                    float et_pwdMaxY = v.getHeight();
                    float x = event.getX();
                    float y = event.getY();

                    if (x < et_pwdMaxX && x > et_pwdMinX && y > et_pwdMinY && y < et_pwdMaxY) {
                        // 点击了眼睛图标的位置
                        isHideFirst = !isHideFirst;
                        if (isHideFirst) {
                            Drawable drawable3 = getResources().getDrawable(R.drawable.xianshi);
                            drawable3.setBounds(0, 0, 60, 40);
                            inputPassword.setCompoundDrawables(drawable, null, drawable3, null);
                            inputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        } else {
                            Drawable drawable2 = getResources().getDrawable(R.drawable.yincang);
                            drawable2.setBounds(0, 0, 60, 40);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
                            inputPassword.setCompoundDrawables(drawable, null, drawable2, null);//只
                            inputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        }
                    }
                }
                        return false;
                    }
                });
        imageView.setOnClickListener(this);
        goto_Register.setOnClickListener(this);
        forget_pw.setOnClickListener(this);
        First_next_button.setOnClickListener(this);
        First_next_button.setEnabled(false);
        inputNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                nl=inputNumber.length();
                pl=inputPassword.length();
                if (nl==11 && pl>5 && cb==1){
                        First_next_button.setEnabled(true);
                        First_next_button.setTextColor(Color.WHITE);
                        First_next_button.setBackgroundResource(R.drawable.begin_textview_shape_change);
                }
                else{
                     First_next_button.setEnabled(false);
                    First_next_button.setTextColor(Color.parseColor("#B8B8B8"));
                    First_next_button.setBackgroundResource(R.drawable.firist_edittext_shape);
                }
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

//18397509607
        inputPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                nl=inputNumber.length();
                pl=inputPassword.length();
                if (nl==11 && pl>5 && cb==1){
                    First_next_button.setEnabled(true);
                    First_next_button.setTextColor(Color.WHITE);
                    First_next_button.setBackgroundResource(R.drawable.begin_textview_shape_change);
                }
                else{
                    First_next_button.setTextColor(Color.parseColor("#B8B8B8"));
                    First_next_button.setEnabled(false);
                    First_next_button.setBackgroundResource(R.drawable.firist_edittext_shape);
                }

            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
//        myCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                if (myCheckBox.isChecked() && canClick==true){
//                    First_next_button.setEnabled(true);
//                    First_next_button.setTextColor(Color.WHITE);
//                    First_next_button.setBackgroundResource(R.drawable.begin_textview_shape_change);
//                    canClick1=true;
//                }else {
//                    canClick1=false;
//                    First_next_button.setEnabled(false);
//                    First_next_button.setBackgroundResource(R.drawable.begin_textview_shape);
//                }
//
//            }
//        });

        SharedPreferences sharedPreferencesfp =getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String Login = sharedPreferencesfp.getString("login", "");
        if(Login.equals("haveLogin")){
            Intent userintent=new Intent(this,MainActivity.class);
            startActivity(userintent);
        }

        login_agent=findViewById(R.id.login_agent);
        login_agent.setOnClickListener(this);
        login_xieyi=findViewById(R.id.login_xieyi);
        login_xieyi.setOnClickListener(this);
        login_zhengce=findViewById(R.id.login_zhengce);
        login_zhengce.setOnClickListener(this);


        Intent intent = getIntent();
        String mobile = intent.getStringExtra("mobile");
        inputNumber.setText(mobile);
        String password = intent.getStringExtra("password");
        inputPassword.setText(password);


        setStatusBar();
    }
    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch(id){
            case R.id.login_xieyi:
                Intent Privacyintent =new Intent(FirstActivity.this, PrivacyActivity.class);
                startActivity(Privacyintent);
                break;

            case R.id.login_zhengce:
                Intent UAintent =new Intent(FirstActivity.this, UserAgreementActivity.class);
                startActivity(UAintent);
                break;
            case R.id.login_agent:
                if(cb==1){
                    cb=2;
                    First_next_button.setTextColor(Color.parseColor("#B8B8B8"));
                    First_next_button.setEnabled(false);
                    First_next_button.setBackgroundResource(R.drawable.firist_edittext_shape);
                    login_agent.setImageResource(R.drawable.cb_fase);
                }else{
                    cb=1;
                    login_agent.setImageResource(R.drawable.cb_true);
                }
                nl=inputNumber.length();
                pl=inputPassword.length();
                if (nl==11 && pl>5 && cb==1){
                    First_next_button.setEnabled(true);
                    First_next_button.setTextColor(Color.WHITE);
                    First_next_button.setBackgroundResource(R.drawable.begin_textview_shape_change);
                }
                break;
            case R.id.register_TV:
                Intent Registeintent=new Intent(FirstActivity.this,RegisterActivity.class);
                startActivity(Registeintent);
                break;
            case R.id.forget_pw:
                    Intent smsintent=new Intent(FirstActivity.this,SmsPasswordActivity.class);
                    startActivity(smsintent);
                break;
            case R.id.imageView_PW:
                int nb_leng = inputNumber.getText().toString().length();
                pw_leng=inputPassword.getText().toString().length();
                if (pW_show==false){
                    pW_show=true;
                    inputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    inputPassword.setSelection(inputPassword.length());
                    imageView.setBackgroundResource(R.drawable.yincang);
                }else{
                    pW_show=false;
                    inputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    inputPassword.setSelection(inputPassword.length());
                    imageView.setBackgroundResource(R.drawable.xianshi);
                }
                if (nb_leng ==11 && pw_leng>=6){
                    First_next_button.setEnabled(true);
                    First_next_button.setBackgroundResource(R.drawable.begin_textview_shape_change);
                }
                break;
            case R.id.first_next_button:
                mCountDownTimer.start();
                gotomain();
                break;
         }
    }
    private CountDownTimer mCountDownTimer = new CountDownTimer(3000, 1000) {
        @Override
        public void onTick(long l) {
            First_next_button.setEnabled(false);
            First_next_button.setText("登录中。。。");
        }

        @Override
        public void onFinish() {
            First_next_button.setEnabled(true);
            First_next_button.setText("登录");
        }
    };
    private void gotomain(){
        String mobile = inputNumber.getText().toString().trim();
        String password = inputPassword.getText().toString().trim();
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/register/login");
        //需要携带的参数
        params.addBodyParameter("mobile", mobile);
        params.addBodyParameter("password", password);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    logCode = jsonObject.optInt("code", 0);
                    Log.e(TAG, "logCode"+logCode);
                    String info = jsonObject.optString("info", null);
                    JSONObject jsonObjec = new JSONObject(info);
                    role= jsonObjec.optString("role", "");
                    userID=jsonObjec.optString("id", "");

//                                JSONObject info = jsonObject.getJSONObject("info");
//                                Log.e(TAG, "info:"+info);
//                                String role = info.optString("role", "");
//                                Log.e(TAG, "role:"+role);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (logCode == 200) {
                    mCountDownTimer.cancel();
                    //刷新缓存值
                    SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //私有数据
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("login", "haveLogin");
                    editor.putString("userID", userID);
                    editor.putString("mobile", mobile);
                    editor.putString("role", role);
                    editor.putString("password", "");
                    editor.putString("listShow", "");
                    editor.putString("incomlistShow", "");
                    editor.putString("headimagepath", "");
                    editor.putString("Signing", "");
                    editor.putString("sign_image", "");
                    editor.putString("Sig_date", "");
                    editor.putString("name", "");
                    editor.putString("money", "");
                    editor.putString("integra", "");
                    editor.putString("start_sn", "");
                    editor.putString("end_sn", "");
                    editor.putInt("points_type",0);
                    editor.putString("exitUser", "");
                    editor.commit();
                    //
                    Intent userintent=new Intent(FirstActivity.this,MainActivity.class);
                    startActivity(userintent);
                }
                if(logCode == 304){
                    mCountDownTimer.cancel();
                    First_next_button.setText("登录");
                    SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //私有数据
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("login", "haveLogin");
                    editor.putString("userID", userID);
                    editor.commit();
                    Intent userintent=new Intent(FirstActivity.this,MainActivity.class);
                    startActivity(userintent);
                    Toast.makeText(getBaseContext().getApplicationContext(), "该账号 在别的设备上登录", Toast.LENGTH_LONG).show();
                } if(logCode == 301){
                    mCountDownTimer.cancel();
                    First_next_button.setText("登录");
                    First_next_button.setEnabled(true);
                     Toast.makeText(getBaseContext().getApplicationContext(), "账号不存在或密码错误", Toast.LENGTH_LONG).show();
                }
                if(logCode == 500){
                    mCountDownTimer.cancel();
                    First_next_button.setText("登录");
                    First_next_button.setEnabled(true);
                     Toast.makeText(getBaseContext().getApplicationContext(), "账号不存在或密码错误", Toast.LENGTH_LONG).show();
                }
                if(logCode == 501){
                    mCountDownTimer.cancel();
                    First_next_button.setText("登录");
                    First_next_button.setEnabled(true);
                     Toast.makeText(getBaseContext().getApplicationContext(), "手机号不能为空", Toast.LENGTH_LONG).show();
                }
                if(logCode == 404){
                    mCountDownTimer.cancel();
                    First_next_button.setText("登录");
                    First_next_button.setEnabled(true);
                     Toast.makeText(getBaseContext().getApplicationContext(), "检查账号或请退出重新进入", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(org.xutils.common.Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
    }
    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
        String strTel = "[1][358]\\d{9}";
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(strTel);
    }


}
